package cn.swing.main.srv.cv.utils;

public class CosineSimilarity {

    public static double calculateCosineSimilarity(double[] color1, double[] color2) {
        if (color1.length != color2.length || color1.length < 3) {
            throw new IllegalArgumentException("Both color arrays must have exactly 3 elements.");
        }

        double dotProduct = 0.0;
        double normA = 0.0;
        double normB = 0.0;

        for (int i = 0; i < color1.length; i++) {
            dotProduct += color1[i] * color2[i];
            normA += Math.pow(color1[i], 2);
            normB += Math.pow(color2[i], 2);
        }

        normA = Math.sqrt(normA);
        normB = Math.sqrt(normB);

        if (normA == 0.0 || normB == 0.0) {
            return 0.0; // To handle the case where one of the vectors is zero
        }

        return dotProduct / (normA * normB);
    }

    public static boolean areColorsSimilar(double[] color1, double[] color2, double threshold) {
        double similarity = calculateCosineSimilarity(color1, color2);
        return similarity >= threshold;
    }

    public static void main(String[] args) {
        double[] color1 = {40.638888888888886, 237.6111111111111, 255}; // Example BGR color
        double[] color2 = {120.125, 244.375, 238.3125}; // Another example BGR color

        double threshold = 0.99; // Threshold for similarity

        double similarity = calculateCosineSimilarity(color1, color2);
        System.out.println("Cosine Similarity: " + similarity);

        boolean areSimilar = areColorsSimilar(color1, color2, threshold);
        System.out.println("Are colors similar? " + areSimilar);
    }

}

